/*
 * Copyright 2011 Karl Pauls karlpauls@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.kalpatec.pojosr.framework.launch;

import java.net.URL;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.logging.Level;

import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;

public class ClasspathScanner
{
	final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(getClass().getName());
		
    public final List<BundleDescriptor> scanForBundles() throws Exception
    {
        return scanForBundles(null, null);
    }

    public final List<BundleDescriptor> scanForBundles(ClassLoader loader) throws Exception
    {
        return scanForBundles(null, loader);
    }

    public final List<BundleDescriptor> scanForBundles(String filterString)
            throws Exception
    {
        return scanForBundles(filterString, null);
    }

    public List<BundleDescriptor> scanForBundles(String filterString, ClassLoader loader)
        throws Exception
    {
        Filter filter = (filterString != null) ? FrameworkUtil
                .createFilter(filterString) : null;

        loader = (loader != null) ? loader : getClass().getClassLoader();

        List<BundleDescriptor> bundles = new ArrayList<BundleDescriptor>();
		
        for (Enumeration<URL> e = 
        		loader.getResources("META-INF/MANIFEST.MF"); e.hasMoreElements();)
        {
            URL manifestURL = e.nextElement();

            try  {
	            Manifest mf = new Manifest(manifestURL.openStream());
	
	            if ((filter == null)
	                    || filter.match(attributesToDictionary(mf.getMainAttributes())))
	            {
	            	
	            	BundleDescriptor dec = new BundleDescriptor(loader, manifestURL.toURI(), mf);
	                bundles.add( dec ) ;
	            }
            }
            catch( Throwable t ) {
            	logger.log( Level.WARNING, String.format("error reading manifest from url\n[%s]", manifestURL));
            	// Ignore error
            }
        }
        return bundles;
    }

    private Dictionary<String,Object> attributesToDictionary( Attributes attr ) {
    	
    	return new Hashtable<String,Object>();
    }
}
